'use client'
import { useState } from 'react'
import styles from './TikTok.module.scss'
import { cn, copyToClipboard, isMobileDevice } from '@/lib/utils'
// import { Toast } from 'antd-mobile'
import { toast } from '@/hooks/use-toast'
import { Language, translations } from '@/lib/i18n'
import {
  Button,
  Tooltip,
  TooltipContent,
  TooltipProvider,
  TooltipTrigger,
} from '@/components/ui'
import CopyIcon from '@/assets/icons/copy.svg'
// 定义标签类型
const Tab = {
  'zh-CN': ['公众号', '小红书', '口播文案'] as const,
  en: ['Official Account', 'Xiaohongshu', 'Script'] as const,
}

const createIcon =
  'https://v-www.oss-cn-chengdu.aliyuncs.com/mto-test/test/31a0908a-464d-4f40-8cde-7d7dda8db56c.png'
const copyIcon =
  'https://v-www.oss-cn-chengdu.aliyuncs.com/mto-test/test/5fb4c19b-5258-4840-9b3b-20a3fce62bca.png'

const Authorization =
  'Bearer pat_CU7jI8gDJH0nFTW7Zk9gm4n6zGUBmMBjP1FhLPDMhPMQ6G0HymKzNR62XDZYCooj'
const headers = {
  'Content-Type': 'application/json',
  Authorization,
  Accept: '*/*',
  Host: 'api.coze.cn',
  Connection: 'keep-alive',
}
const defaultFontArr = [
  { label: '500', value: 500 },
  { label: '1000', value: 1000 },
  { label: '1500', value: 1500 },
  { label: '2000', value: 2000 },
  { label: '2500', value: 2500 },
  { label: '5000', value: 5000 },
]

const scriptFontArr = [
  { label: '150', value: 150 },
  { label: '250', value: 250 },
  { label: '500', value: 500 },
]

const advancedOptions = {
  'zh-CN': [
    { label: '去AI味', value: 'clear_ai' },
    { label: '宣传&SEO', value: 'seo' },
  ],
  en: [
    { label: 'Remove AI Traces', value: 'clear_ai' },
    { label: 'Promotion & SEO', value: 'seo' },
  ],
} as const

const styleArr = {
  'zh-CN': [
    '智能匹配',
    '专业严谨',
    '生动有趣',
    '通俗易懂',
    '情感共鸣',
    '个性化风格',
  ] as const,
  en: [
    'Smart Match',
    'Professional',
    'Vivid & Fun',
    'Easy to Understand',
    'Emotional',
    'Personalized',
  ] as const,
}

interface Props {
  index?: number
  lang?: Language
}

interface Params {
  word_count: number
  link: string
  style: string
  result: string
  publish_platform: string
  clear_ai: boolean
  seo: boolean
  [key: string]: string | number | boolean
}

// 在文件顶部添加 TextDecoder
const decoder = new TextDecoder()

const Index = () => {
  const index = 1
  const lang = 'en'
  const t = translations[lang]
  // 添加新的状态
  const [analysisContent, setAnalysisContent] = useState('')
  const [isAnalyzing, setIsAnalyzing] = useState(false)

  // 原有的状态
  const [params, setParams] = useState<Params>({
    word_count: 2000,
    link: '',
    style: styleArr[lang][0],
    result: '',
    publish_platform: Tab[lang][0],
    clear_ai: false,
    seo: false,
  })

  const getFontArr = () => {
    return params.publish_platform === Tab[lang][2] ? scriptFontArr : defaultFontArr
  }

  const handlePlatformChange = (platform: string) => {
    const newWordCount = platform === Tab[lang][2] ? 150 : 2000
    setParams({
      ...params,
      publish_platform: platform,
      word_count: newWordCount,
    })
  }

  // const analyzeContent = async () => {
  //   if (!params.link) return

  //   setIsAnalyzing(true)
  //   setAnalysisContent('')

  //   try {
  //     const response = await fetch('https://api.coze.cn/v3/chat', {
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'application/json',
  //         Authorization: Authorization,
  //         // Authorization:
  //         //   'Bearer pat_dUuv1jYvus384ygZDJsnXgCK8ucGmYKh6rzAFZUnrF61eDmAQYOsXN32PCbCwHPO',
  //         Accept: '*/*',
  //         Host: 'api.coze.cn',
  //         Connection: 'keep-alive',
  //       },
  //       body: JSON.stringify({
  //         bot_id: '7390657389861027867',
  //         user_id: '666',
  //         stream: true,
  //         additional_messages: [
  //           {
  //             role: 'user',
  //             content: params.link,
  //             content_type: 'text',
  //           },
  //         ],
  //       }),
  //     })

  //     if (!response.ok) {
  //       throw new Error(`HTTP error! status: ${response.status}`)
  //     }

  //     const reader = response.body?.getReader()
  //     if (!reader) return

  //     while (true) {
  //       const { value, done } = await reader.read()
  //       if (done) break

  //       const chunk = decoder.decode(value)
  //       const lines = chunk.split('\n')

  //       for (const line of lines) {
  //         if (line.trim() === '') continue

  //         if (line.startsWith('event:conversation.message.delta')) {
  //           const nextLine = lines[lines.indexOf(line) + 1]
  //           if (nextLine?.startsWith('data:')) {
  //             try {
  //               const data = JSON.parse(nextLine.slice(5))
  //               if (data.content) {
  //                 setAnalysisContent((prev) => prev + data.content)
  //               }
  //             } catch (e) {
  //               console.error('Parse error:', e)
  //             }
  //           }
  //         }
  //       }
  //     }
  //   } catch (error) {
  //     console.error('Analysis error:', error)
  //     // Toast.show({
  //     //   content: lang === 'zh-CN' ? '解析失败' : 'Analysis failed',
  //     //   icon: 'error',
  //     // })
  //     toast({
  //       title: lang === 'zh-CN' ? '解析失败' : 'Analysis failed',
  //       variant: 'destructive',
  //     })
  //   } finally {
  //     setIsAnalyzing(false)
  //   }
  // }

  const create = async () => {
    if (!params.link) return

    // 立即开始内容解析
    // analyzeContent()
    setIsAnalyzing(true)
    setAnalysisContent('')

    // 显示生成文章的 loading
    // const loadingToast = Toast.show({
    //   content: t.common.loading,
    //   icon: 'loading',
    //   duration: 0,
    // })
    const toastInstance = toast({
      title: t.common.loading,
      duration: Infinity,
    })
    try {
      const { link: url, word_count, publish_platform, clear_ai, seo } = params
      const response = await fetch('https://api.coze.cn/v1/workflow/run', {
        method: 'POST',
        headers,
        body: JSON.stringify({
          workflow_id: '7452998572197822502',
          parameters: { url, word_count, publish_platform, clear_ai, seo },
          bot_id: '7440022107356643347',
        }),
      })
      toastInstance.dismiss()

      const result = await response.json()
      // loadingToast.close()

      if (result.code) {
        // return Toast.show({
        //   content: result.msg,
        //   icon: 'error',
        // })
        return toast({
          title: result.msg,
          variant: 'destructive',
        })
      }
      let content = ''
      try {
        const parseJson = JSON.parse(result.data)
        content = parseJson?.data || parseJson.rewrite
        // console.log('parseJson.original:', parseJson.original)
        // console.log('parseJson.rewrite:', parseJson.rewrite)
        setAnalysisContent(parseJson.original)
      } catch (error) {
        console.error(error)
      }
      setParams({
        ...params,
        result: content,
      })

      // Toast.show({
      //   content: t.common.success,
      //   icon: 'success',
      // })
      toast({
        title: t.common.success,
        duration: 3000,
      })
    } catch (error) {
      // loadingToast.close()
      console.error('Error:', error)
      // Toast.show({
      //   content: lang === 'zh-CN' ? '请求失败' : 'Request failed',
      //   icon: 'error',
      // })
      toast({
        title: lang === 'zh-CN' ? '请求失败' : 'Request failed',
        variant: 'destructive',
        duration: 3000,
      })
    } finally {
      setIsAnalyzing(false)
    }
  }

  return (
    <div
      style={{ display: index === 1 ? 'flex' : 'none' }}
      className={cn(styles.TikTok, '!p-4 !pt-1')}
    >
      <div className={styles.content}>
        <div className={styles.top}>
          <div className={cn(styles.left, 'space-y-4')}>
            <div className="bg-white/10 rounded-lg p-4 border border-[#B9AEFF]/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Original Link/Content
              </div>
              <textarea
                value={params.link}
                onChange={(e) => setParams({ ...params, link: e.target.value })}
                className="w-full bg-black/40 rounded-[10px] h-[120px] text-white/80 placeholder:text-white/40 text-sm outline-none p-2.5"
                placeholder="Please paste TikTok link/text content"
                rows={6}
                style={{ resize: 'none' }}
              />
            </div>
            <div className="bg-white/10 rounded-lg p-4 border border-[#B9AEFF]/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Article Type
              </div>
              <div className="flex gap-2">
                {Tab[lang].map((v, k) => (
                  <span
                    key={k}
                    className={cn(
                      'flex items-center rounded-[10px] h-7 bg-black/40 px-2.5 text-sm text-white/80 border border-transparent cursor-pointer',
                      params.publish_platform === v &&
                        'border-[#A091FD] text-[#A091FD]',
                    )}
                    onClick={() => handlePlatformChange(v)}
                  >
                    {v}
                  </span>
                ))}
              </div>
            </div>
            <div className="bg-white/10 rounded-lg p-4 border border-[#B9AEFF]/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Article word count
              </div>
              <div className="flex flex-wrap gap-2">
                {getFontArr().map((v, k) => (
                  <span
                    key={k}
                    className={cn(
                      'flex items-center rounded-[10px] h-7 bg-black/40 px-2.5 text-sm text-white/80 border border-transparent cursor-pointer',
                      params.word_count === v.value &&
                        'border-[#A091FD] text-[#A091FD]',
                    )}
                    onClick={() => setParams({ ...params, word_count: v.value })}
                  >
                    {v.label} words
                  </span>
                ))}
                <input
                  value={params.word_count}
                  onChange={(e) =>
                    setParams({ ...params, word_count: Number(e.target.value) })
                  }
                  type="number"
                  placeholder="Custom count"
                  className={cn(
                    'flex items-center w-24 rounded-[10px] h-7 bg-black/40 px-2.5 text-sm text-white/80 border border-transparent outline-none',
                    'focus:border-[#A091FD] hover:border-[#A091FD] focus:text-[#A091FD] hover:text-[#A091FD]',
                  )}
                />
              </div>
            </div>
            <div className="bg-white/10 rounded-lg p-4 border border-[#B9AEFF]/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Advanced Options
              </div>
              <div className="flex gap-2">
                {advancedOptions[lang].map((v, k) => (
                  <span
                    key={k}
                    className={cn(
                      'flex items-center rounded-[10px] h-7 bg-black/40 px-2.5 text-sm text-white/80 border border-transparent cursor-pointer',
                      params[v.value] && 'border-[#A091FD] text-[#A091FD]',
                    )}
                    onClick={() =>
                      setParams({ ...params, [v.value]: !params[v.value] })
                    }
                  >
                    {v.label}
                  </span>
                ))}
              </div>
            </div>
            <div className="bg-white/10 rounded-lg p-4 border border-[#B9AEFF]/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Writing Style
              </div>
              <div className="flex flex-wrap gap-2">
                {styleArr[lang].map((v, k) => (
                  <span
                    key={k}
                    className={cn(
                      'flex items-center rounded-[10px] h-7 bg-black/40 px-2.5 text-sm text-white/80 border border-transparent cursor-pointer',
                      params.style === v && 'border-[#A091FD] text-[#A091FD]',
                    )}
                    onClick={() => setParams({ ...params, style: v })}
                  >
                    {v}
                  </span>
                ))}
              </div>
              <textarea
                value={params.style}
                onChange={(e) => setParams({ ...params, style: e.target.value })}
                placeholder="Please describe the writing style or input a sample article. I will follow your described style or mimic the style of your input article for personalized creation"
                className="w-full mt-4 bg-black/40 rounded-[10px] h-[120px] text-white/80 placeholder:text-white/40 text-sm outline-none p-2.5 resize-none"
                rows={4}
              />
            </div>
            <div className="flex gap-4">
              <div className="flex-1 px-4">
                <Button
                  className="w-full rounded-full h-11 disabled:bg-white/10 disabled:text-white/40"
                  size="lg"
                  onClick={() => params.link && create()}
                  disabled={!params.link}
                >
                  Generate Article
                </Button>
              </div>
              {/* <div className="flex-1">
                <Button
                  className="w-full rounded-full"
                  size="lg"
                  variant="secondary"
                  disabled={!params.result}
                  onClick={() => {
                    copyToClipboard()
                    toast({
                      title: t.common.success,
                    })
                  }}
                >
                  Copy Article
                </Button>
              </div> */}
            </div>
            {/* {isMobileDevice() && (
              <div
                onClick={() => params.link && create()}
                className={`${styles.create} ${!params.link && styles.check}`}
              >
                {lang === 'zh-CN' ? '生成文章' : 'Generate Article'}
              </div>
            )} */}
          </div>
          <div className={styles.middle}>
            <div className="bg-white/10 flex flex-col h-full rounded-lg p-4 border border-white/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium flex justify-between">
                <span>Generated Article</span>
                <TooltipProvider>
                  <Tooltip>
                    <TooltipTrigger asChild>
                      <CopyIcon
                        className={cn(
                          'w-4 h-4 cursor-pointer',
                          !params.result && 'opacity-50 cursor-not-allowed',
                        )}
                        onClick={() => {
                          if (!params.result) {
                            return
                          }
                          copyToClipboard()
                          toast({ title: t.common.success })
                        }}
                      />
                    </TooltipTrigger>
                    <TooltipContent>
                      {!params.result ? 'Please generate first' : 'Copy Article'}
                    </TooltipContent>
                  </Tooltip>
                </TooltipProvider>
              </div>
              <div
                id="content"
                className="bg-black/40 rounded-lg p-2.5 text-white/80 text-sm flex-1 overflow-y-auto"
              >
                {!params.result && (
                  <span className="text-white/20">Results will be shown here</span>
                )}
                <div
                  dangerouslySetInnerHTML={{
                    __html: params.result.replace('```html', '').replace('```', ''),
                  }}
                />
              </div>
            </div>
          </div>
          <div className={styles.right}>
            <div className="bg-white/10 flex flex-col h-full rounded-lg p-4 border border-white/10">
              <div className="pb-2.5 text-white/80 text-sm font-medium">
                Content Analysis
              </div>
              <div className="bg-black/40 rounded-lg p-2.5 text-white/80 text-sm flex-1 overflow-y-auto">
                {isAnalyzing ? (
                  <span className="text-white/20">Analyzing...</span>
                ) : !analysisContent ? (
                  <span className="text-white/20">
                    Analysis results will be shown here
                  </span>
                ) : (
                  <div>{analysisContent}</div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* {!isMobileDevice() && (
          <div className={styles.bottom}>
            <img
              onClick={() => params.link && create()}
              className={`${!params.link ? styles.check : ''}`}
              src={createIcon}
              alt={lang === 'zh-CN' ? '生成' : 'Generate'}
            />
            <img
              className={`${!params.result ? styles.check : ''}`}
              onClick={() => {
                if (!params.result) {
                  // return Toast.show({
                  //   content:
                  //     lang === 'zh-CN' ? '请生成后再复制' : 'Please generate first',
                  // })
                  return toast({
                    title:
                      lang === 'zh-CN' ? '请生成后再复制' : 'Please generate first',
                    variant: 'destructive',
                  })
                }

                copyToClipboard()
                // Toast.show({
                //   content: t.common.success,
                //   icon: 'success',
                // })
                toast({
                  title: t.common.success,
                })
              }}
              src={copyIcon}
              alt={lang === 'zh-CN' ? '复制' : 'Copy'}
            />
          </div>
        )} */}
      </div>
    </div>
  )
}

export default Index
